package pad.com.haidiyun.www.boothprint;

import android.app.IntentService;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.zc.http.okhttp.OkHttpUtils;
import com.zc.http.okhttp.callback.StringCallback;
import com.zc.http.okhttp.request.RequestCall;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.MediaType;
import pad.com.haidiyun.www.bean.DishTableBean;
import pad.com.haidiyun.www.boothprint.print.GPrinterCommand;
import pad.com.haidiyun.www.boothprint.print.PrintPic;
import pad.com.haidiyun.www.boothprint.print.PrintQueue;
import pad.com.haidiyun.www.boothprint.print.PrintUtil;
import pad.com.haidiyun.www.boothprint.printutil.PrintOrderDataMaker;
import pad.com.haidiyun.www.boothprint.printutil.PrinterWriter;
import pad.com.haidiyun.www.boothprint.printutil.PrinterWriter58mm;
import pad.com.haidiyun.www.common.Common;
import pad.com.haidiyun.www.common.FileUtils;
import pad.com.haidiyun.www.common.P;
import pad.com.haidiyun.www.common.U;
import pad.stand.com.haidiyun.www.common.SharedUtils;

/**
 * Created by liuguirong on 8/1/17.
 * <p/>
 * print ticket service
 */
public class BtService extends IntentService {

    public BtService() {
        super("BtService");
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public BtService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent == null || intent.getAction() == null) {
            return;
        }
        if (intent.getAction().equals(PrintUtil.ACTION_PRINT_TEST)) {
            printTest();
        } else if (intent.getAction().equals(PrintUtil.ACTION_PRINT_TEST_TWO)) {
            printTesttwo(3);
        } else if (intent.getAction().equals(PrintUtil.ACTION_PRINT_BITMAP)) {
            printBitmapTest();
        }

    }

    private void printTest() {
        sharedUtils = new SharedUtils(Common.CONFIG);
        loadNet();
    }

    /**
     * 打印几遍
     *
     * @param num
     */
    private void printTesttwo(int num) {
        try {
            ArrayList<byte[]> bytes = new ArrayList<byte[]>();
            for (int i = 0; i < num; i++) {
                String message = "蓝牙打印测试\n蓝牙打印测试\n蓝牙打印测试\n\n";
                bytes.add(GPrinterCommand.reset);
                bytes.add(message.getBytes("gbk"));
                bytes.add(GPrinterCommand
                        .print);
                bytes.add(GPrinterCommand.print);
                bytes.add(GPrinterCommand.print);
            }
            PrintQueue.getQueue(getApplicationContext()).add(bytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void print(byte[] byteArrayExtra) {
        if (null == byteArrayExtra || byteArrayExtra.length <= 0) {
            return;
        }
        PrintQueue.getQueue(getApplicationContext()).add(byteArrayExtra);
    }

    private void printBitmapTest() {
        BufferedInputStream bis;
        try {
            bis = new BufferedInputStream(getAssets().open(
                    "icon_empty_bg.bmp"));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Bitmap bitmap = BitmapFactory.decodeStream(bis);
        PrintPic printPic = PrintPic.getInstance();
        printPic.init(bitmap);
        if (null != bitmap) {
            if (bitmap.isRecycled()) {
                bitmap = null;
            } else {
                bitmap.recycle();
                bitmap = null;
            }
        }
        byte[] bytes = printPic.printDraw();
        ArrayList<byte[]> printBytes = new ArrayList<byte[]>();
        printBytes.add(GPrinterCommand.reset);
        printBytes.add(GPrinterCommand.print);
        printBytes.add(bytes);
        Log.e("BtService", "image bytes size is :" + bytes.length);
        printBytes.add(GPrinterCommand.print);
        PrintQueue.getQueue(getApplicationContext()).add(bytes);
    }

    //
//    private void printPainting() {
//        byte[] bytes = PrintPic.getInstance().printDraw();
//        ArrayList<byte[]> printBytes = new ArrayList<byte[]>();
//        printBytes.add(GPrinterCommand.reset);
//        printBytes.add(GPrinterCommand.print);
//        printBytes.add(bytes);
//        Log.e("BtService", "image bytes size is :" + bytes.length);
//        printBytes.add(GPrinterCommand.print);
//        PrintQueue.getQueue(getApplicationContext()).add(bytes);
//    }
    private SharedUtils sharedUtils;
    private RequestCall requestCall;
    private ArrayList<DishTableBean> billTableBeans;


    /**
     * 加载网络中的菜单
     */
    private boolean loadNet() {
        billTableBeans = new ArrayList<DishTableBean>();
        String ip = sharedUtils.getStringValue("IP");
        String billId = sharedUtils.getStringValue("billId");
        if (billId.length() == 0) {
            return false;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("data", billId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        requestCall = OkHttpUtils.postString()
                .url(U.VISTER(ip, U.URL_GET_ORDER))
                .mediaType(MediaType.parse("application/getBasicData; charset=utf-8"))
                .content(jsonObject.toString())
                .build();
        requestCall.execute(netCallback);
        return true;
    }

    private StringCallback netCallback = new StringCallback() {

        @Override
        public void onResponse(String response, int id) {
            // TODO Auto-generated method stub
            try {
                JSONObject jsonObject = new JSONObject(FileUtils.formatJson(response));
                P.c("已下单:" + jsonObject.toString());
                if (jsonObject.getBoolean("Success")) {
                    //成功
                    JSONArray jsonArray = jsonObject.getJSONArray("Data");
                    String data = jsonArray.toString();
                    int len = jsonArray.length();
                    if (len != 0) {
                        billTableBeans.clear();
                    }
                    for (int i = 0; i < len; i++) {
                        //已下单菜品
                        JSONObject object = jsonArray.getJSONObject(i);
                        DishTableBean tableBean = new DishTableBean();
                        tableBean.setCode(object.getString("MenuCode"));
                        tableBean.setName(object.getString("MenuName"));
                        tableBean.setCount(object.getInt("Number"));
                        tableBean.setPrice(object.getDouble("Price"));
                        tableBean.setUnit(object.getString("Unit"));
                        tableBean.setCook_names(object.getString("Cooks"));
                        tableBean.setRemark(object.getString("Remark"));
                        billTableBeans.add(tableBean);

                    }
                    double price = process(true);
                    P.c("总价:" + price);
                    PrintOrderDataMaker printOrderDataMaker = new PrintOrderDataMaker(BtService.this, "", PrinterWriter58mm.TYPE_58, PrinterWriter.HEIGHT_PARTING_DEFAULT, data, price);
                    ArrayList<byte[]> printData = (ArrayList<byte[]>) printOrderDataMaker.getPrintData(PrinterWriter58mm.TYPE_58);
                    PrintQueue.getQueue(getApplicationContext()).add(printData);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(Call call, Exception e, int id) {
            P.c(e.toString());
        }
    };

    /**
     * 计算已下单
     *
     * @return
     */
    private double process(boolean noSend) {
        // 计算总价
        int len = billTableBeans.size();
        double total = 0;
        for (int i = 0; i < len; i++) {
            DishTableBean obj = billTableBeans.get(i);
            total += (obj.getCount() * obj.getPrice());
        }
        return format(total);
    }

    private double format(double total) {
        BigDecimal b = new BigDecimal(total);
        // 保留2位小数
        double total_v = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return total_v;
    }
}